package com.bluemson.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(filterName = "CrossFilter")
public class CrossFilter implements Filter{
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //允许跨域的域名。单个域名、*(匹配所有域名)
        //request.getHeader("Origin") 即直接获取请求头的origin的值，即请求方的域名
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));

        //若要使用cookie，需要设置值为true，表示允许发送cookie（可选）
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        //服务器支持的所有请求头字段
        resp.setHeader("Access-Control-Allow-Headers",
                "Origin," +
                        "Access-Control-Request-Headers," +
                        "Access-Control-Allow-Headers," +
                        "Content-Type," +
                        "Keep-Alive," +
                        "User-Agent," +
                        "Cache-Control," +
                        "Cookie," +

                        "DNT," +
                        "X-Requested-With," +
                        "X-Mx-ReqToken," +
                        "X-Requested-With," +
                        "If-Modified-Since," +
                        "Accept," +
                        "Connection," +
                        "X-XSRF-TOKEN," +
                        "X-CSRF-TOKEN," +
                        "Authorization");

        //（预检请求）的响应结果，规定了服务器允许客户端使用的请求方法， 如：POST, GET 和 OPTIONS
        resp.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");

        //设置（预检请求）的返回结果的过期时间，这里设置响应最大有效时间为 86400 秒，即24 小时
        //即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息可以被缓存多久
        resp.setHeader("Access-Control-Max-Age", "86400");

        //设置除了简单响应首部以外，需要暴露给外部的其他首部
        resp.setHeader("Access-Control-Expose-Headers", "Authorization");

        chain.doFilter(req, resp);
    }
}
